import React, { useRef, useState, useEffect } from "react";
import styled from "styled-components";

const CanvasDIV = styled.div`
  width: 100%;
  height: 100%;
  position: relative;
  .center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
`;
const Bg = (props) => {
  // 实现插槽
  let children = React.Children.toArray(props.children);
  let panel = [];
  children.forEach((item) => {
    if (item.props.slot === "panel") {
      panel.push(item);
    }
  });

  let canvasRef = useRef();

  let [width, setWidth] = useState(window.innerWidth),
    [height, setHeight] = useState(window.innerHeight);
  /**
   * 随机生成颜色
   * @returns
   */
  const getRandomColor = () => {
    const colors = [
      "#33b5e5",
      "#0099cc",
      "#e0441b",
      "#34495e",
      "#2ecc71",
      "#3498db",
      "#e74c3c",
      "#9b59b6",
      "#ecf0f1",
      "#95a5a6",
      "#f39c12",
      "#d35400",
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  };
  /**
   *随机生成26个字母
   * @returns
   */
  const getRandomText = () => {
    let textArr = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "n",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
    ];
    return textArr[Math.floor(Math.random() * textArr.length)];
  };
  const draw = (ctx, columnWidth, columnTextNextIndex) => {
    ctx.fillStyle = `rgba(240,240,240,.1)`; //刷淡上一次内容
    ctx.fillRect(0, 0, width, height); //清空上一次绘制的内容
    ctx.fillStyle = getRandomColor(); //随机色
    ctx.font = `${columnWidth}px 隶书`; //宽高
    for (let i = 0; i < columnTextNextIndex.length; i++) {
      let x = columnWidth * i; //列的位置
      let y = columnTextNextIndex[i] * columnWidth; //行的位置
      ctx.fillText(getRandomText(), x, y);
      if (y >= height && Math.random() > 0.95) {
        columnTextNextIndex[i] = 0;
      } else {
        columnTextNextIndex[i]++; //行的下标++，从下一行开始绘制
      }
    }
  };
  useEffect(() => {
    //代码初始化的时候执行绘制canvas操作
    let canvas = canvasRef.current;
    // 定义canvas的宽高;
    canvas.width = width;
    canvas.height = height;

    let ctx = canvas.getContext("2d");
    //   定义每列字符宽度
    let columnWidth = 30;
    //每列文字数量
    let columnCount = Math.ceil(canvas.width / 30);
    //一列中文字存放的数组长度
    let columnTextNextIndex = new Array(columnCount);
    columnTextNextIndex.fill(0);
    //开启定时器绘制文字
    let timer = setInterval(() => {
      draw(ctx, columnWidth, columnTextNextIndex);
    }, 50);
    return () => {
      console.log("销毁定时器");
      //销毁定时器
      clearInterval(timer);
      timer = null;
    };
  }, []);

  return (
    <CanvasDIV>
      <canvas ref={canvasRef}></canvas>
      <div className="center">{panel}</div>
    </CanvasDIV>
  );
};

export default Bg;
